package com.shuai.baibi.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shuai.baibi.common.BaseResponse;
import com.shuai.baibi.common.ErrorCode;
import com.shuai.baibi.constant.FileConstant;
import com.shuai.baibi.constant.UserConstant;
import com.shuai.baibi.exception.BusinessException;
import com.shuai.baibi.model.entity.Chart;
import com.shuai.baibi.model.entity.ChartAnnex;
import com.shuai.baibi.model.entity.User;
import com.shuai.baibi.model.vo.UserVO;
import com.shuai.baibi.service.ChartAnnexService;
import com.shuai.baibi.service.FileService;
import com.shuai.baibi.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.file.Files;

@RequestMapping("/common")
@RestController
@Slf4j
public class FileController {
    @Autowired
    private ChartAnnexService chartAnnexService;

    @Autowired
    private FileService fileService;


    @Value(value = "${annex.storage-path}")
    private String annexStoragePath;


    @RequestMapping("/file/upload")
    public BaseResponse<Boolean> uploadFile(MultipartFile file, HttpServletRequest request) {
        if (!fileService.checkFileStyle(file)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式错误或大小超限(" + FileConstant.FILE_SIZE_MB + ")");
        }
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件名不能为空");
        }
        if (originalFilename.length() > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件名过长");
        }


        UserVO userVO = (UserVO) request.getSession(false).getAttribute(UserConstant.LOGIN_STATE_KEY);
        Chart chart = new Chart();
        chart.setUserId(userVO.getId());
        fileService.uploadFileSingle(file, chart);
        return ResultUtils.success(Boolean.TRUE);
    }

    /**
     * 根据图表Id下载上传的最新附件
     *
     * @param chartId 图表ID
     * @return 返回上传的最新附件文件
     */
    @RequestMapping("/file/download_single")
    public void downloadFileSingle(Long chartId, HttpServletResponse response, HttpServletRequest request) {
        if (chartId == null || chartId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO = (UserVO) request.getSession(false).getAttribute(UserConstant.LOGIN_STATE_KEY);
        // 查询附件信息表中的附件信息
        LambdaQueryWrapper<ChartAnnex> chartAnnexWrapper = new LambdaQueryWrapper<>();
        chartAnnexWrapper.eq(ChartAnnex::getChartId, chartId);
        chartAnnexWrapper.eq(ChartAnnex::getIsLasted, ChartAnnex.Y);
        ChartAnnex chartAnnex = chartAnnexService.getOne(chartAnnexWrapper);
        if (chartAnnex == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "资源不存在！");
        }
        if (!(chartAnnex.getUserId().equals(userVO.getId()))) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "权限校验失败！");
        }
        String storageName = chartAnnex.getStorageName();   // 获得文件存储名称
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File downloadFile = new File(annexStoragePath + storageName);
            if (!downloadFile.exists()) {
                log.error("下载的文件不存在！file:{}", chartAnnex.getAnnexName());
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "下载的文件不存在");
            }
            inputStream = Files.newInputStream(downloadFile.toPath());
            outputStream = response.getOutputStream();

            // 传输文件
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }

            log.info("用户下载了文件file:{}", chartAnnex.getAnnexName());

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    /**
     * 根据图表Id下载上传的最新附件
     *
     * @param chartId 图表ID
     * @return 返回上传的最新附件文件
     */
    @RequestMapping("/file/download")
    public void downloadFile(Long chartId, HttpServletResponse response, HttpServletRequest request) {
        if (chartId == null || chartId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        HttpSession session = request.getSession(false);
        UserVO userVO = (UserVO) session.getAttribute(UserConstant.LOGIN_STATE_KEY);
        // 查询附件信息表中的附件信息
        LambdaQueryWrapper<ChartAnnex> chartAnnexWrapper = new LambdaQueryWrapper<>();
        chartAnnexWrapper.eq(ChartAnnex::getChartId, chartId);
        chartAnnexWrapper.eq(ChartAnnex::getIsLasted, ChartAnnex.Y);
        ChartAnnex chartAnnex = chartAnnexService.getOne(chartAnnexWrapper);
        if (chartAnnex == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "资源不存在！");
        }
        if (!(chartAnnex.getUserId().equals(userVO.getId()))) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "权限校验失败！");
        }
        String storageName = chartAnnex.getStorageName();   // 获得文件存储名称
        fileService.downLoadFileFromFileServer(storageName, response);
    }
}
